<template>
    <el-dialog
        v-model="dialogVisible"
        :title="type === 'add' ? '新增用户' : '编辑用户'"
        width="500px"
        @close="handleClose"
    >
        <el-form
            ref="formRef"
            :model="userForm"
            :rules="rules"
            label-width="100px"
        >
            <el-form-item label="用户账号" prop="account">
                <el-input v-model="userForm.account" placeholder="请输入用户账号" />
            </el-form-item>
            <el-form-item label="用户昵称" prop="nickName">
                <el-input v-model="userForm.nickName" placeholder="请输入用户昵称" />
            </el-form-item>
            <el-form-item label="手机号码" prop="phone">
                <el-input v-model="userForm.phone" placeholder="请输入手机号码" />
            </el-form-item>
            <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="userForm.sex">
                    <el-radio value="男">男</el-radio>
                    <el-radio value="女">女</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="地址" prop="address">
                <el-input v-model="userForm.address" placeholder="请输入地址" />
            </el-form-item>
            <el-form-item label="头像" prop="picture">
                <el-input v-model="userForm.picture" placeholder="请输入头像地址" />
            </el-form-item>
            <el-form-item label="角色" prop="roleUUID">
                <el-select v-model="userForm.roleUUID" placeholder="请选择角色" style="width: 100%">
                    <el-option
                        v-for="item in roleList"
                        :key="item.uUID"
                        :label="item.roleName"
                        :value="item.uUID"
                    />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { Create, Update, type User } from '@/apis/user'
import type { UserRole } from '@/apis/role'

const props = defineProps<{
    modelValue: boolean
    type: 'add' | 'edit'
    userData?: User
    roleList: UserRole[]
}>()

const emit = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
    (e: 'success'): void
}>()

// 状态变量
const dialogVisible = ref(props.modelValue)
const submitLoading = ref(false)
const formRef = ref<FormInstance>()

// 表单数据
const defaultForm: User = {
    nickName: '',
    account: '',
    phone: '',
    sex: '男',
    address: '',
    picture: '',
    roleUUID: '',
    roleName: '',
    points: '0',
    disable: 1,
    updateTime: '',
    uUID: ''
}

const userForm = ref<User>({ ...defaultForm })

// 表单校验规则
const rules = {
    account: [
        { required: true, message: '请输入用户账号', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    nickName: [
        { required: true, message: '请输入用户昵称', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '请输入手机号码', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    roleUUID: [
        { required: true, message: '请选择角色', trigger: 'change' }
    ]
}

// 监听对话框显示状态
watch(() => props.modelValue, (val) => {
    dialogVisible.value = val
})

watch(() => dialogVisible.value, (val) => {
    emit('update:modelValue', val)
})

// 监听编辑数据
watch(() => props.userData, (val) => {
    if (val) {
        userForm.value = { ...val }
        if (!userForm.value.roleUUID) {
            userForm.value.roleUUID = ''
            userForm.value.roleName = ''
        }
    } else {
        userForm.value = { ...defaultForm }
    }
}, { immediate: true })

// 监听角色选择变化
watch(() => userForm.value.roleUUID, (val) => {
    if (val) {
        const role = props.roleList.find(r => r.uUID === val)
        if (role) {
            userForm.value.roleName = role.roleName
        }
    } else {
        userForm.value.roleName = ''
    }
})

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return
    
    await formRef.value.validate(async (valid, fields) => {
        if (!valid) return
        
        submitLoading.value = true
        try {
            if (props.type === 'add') {
                await Create(userForm.value)
                ElMessage.success('新增成功')
            } else {
                await Update(userForm.value)
                ElMessage.success('更新成功')
            }
            handleClose()
            emit('success')
        } catch (error) {
            console.error('操作失败:', error)
            ElMessage.error('操作失败')
        } finally {
            submitLoading.value = false
        }
    })
}

// 关闭对话框
const handleClose = () => {
    dialogVisible.value = false
    formRef.value?.resetFields()
    userForm.value = { ...defaultForm }
}
</script>

<style scoped lang="scss">
.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 8px;
}
</style> 